<template>
  <div class="scroll-wrap">
    <div ref="oScrollMain" class="scroll-main">
      <slot></slot>
    </div>
  </div>
</template>

<script>
  let t = null; //  用来接收 计时器执行的
  const interval = 10;  //  10s 执行一次计时器

  export default {
    name: 'ScrollWrap',
    props: {
      // propIndex: { type: Number | String, default: 0 }
      propIndex: 0,
      propDelay: 1000,
      buttonStatus: 'prev'  //  向前滚动
    },
    data() {
      return {
        pageIndex: this.propIndex
      }
    },
    watch: {  //  监听 propIndex 值的变化，判断当前是否需要进行切换
      propIndex(val) { 
        this.pageIndex = val;
        this.handleAnimation();
      },
    },
    methods: {
      //  点击上一个按钮
      handleClickPrev() {
        const oScrollMain = this.$refs.oScrollMain;
        if(this.pageIndex == 0) oScrollMain.scrollTo(0, 1000); 
      },
      //  点击下一页按钮
      handleClickNext() {

      },
      //  运动
      handleAnimation() {
        const oScrollMain = this.$refs.oScrollMain;
        const itemHeight = parseFloat(getComputedStyle(oScrollMain, null)['height']);

        //  计算数量
        const count = this.propDelay / interval;
        //  计算元素滚动的距离
        const top = oScrollMain.scrollTop;
        //  计算总长度
        const curLen = this.pageIndex * itemHeight; 
        //  记录需要滚动的长度
        const len = curLen - top;
        //  记录档期执行到了哪
        let position = 0;
        let step = 0;

        console.log(top);
        if(t) clearInterval(t);
        
        t = setInterval(() => {
          //  计算步长
          if(position % 2) {
            step = Math.ceil(len / count); //  向上取整
          } else {
            step = Math.floor(len / count); //  向下取整
          }
          
          oScrollMain.scrollBy(0, step);

          //  Math.abs 绝对值
          if(++position > count) {
            oScrollMain.scrollTo(0, curLen); //  矫正
            clearInterval(t);
            t = null;
          }
        }, interval);
      }
    }
  }
</script>

<style scoped>
  .scroll-wrap {
    position: relative;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    overflow: hidden;
  }

  .scroll-main {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    overflow: auto;  /* 不需要的情况隐藏滚动条 */
  }
</style>